# -*- coding: utf-8 -*-
import logging
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import global_setting
import base64
import zlib

import uuid
#from xmw import error
from google.appengine.ext import db
import datetime
import logging
import error
from appengine_utilities import sessions

class XmlRpcWrapper():
    """
    This class acts as a wrapper around a python object. It copies
    the underlying objects methods so they can be made avaliable to the XmlRpcServer class
    If the methods are public, the first argument "meta" is stripped off of the call from the 
    XMLRpcServer object, so that we can use a generic underlying object for the api call. 
    Private methods (i.e. those starting with an "_" are copied as is, as they are not exposed as
    remote procedures
    """
    def __init__(self, obj):
        self._obj=obj
        for a in dir(obj):
            m=getattr(obj, a)
            if callable(m) and a[0]!="_":
                    self.__dict__[a] = self._call_api_method(a)
                    self.__dict__[a].__doc__ = m.__doc__
                                
    def _call_api_method(self, method):
        return lambda meta, *args, **kwds: getattr(self._obj, method)(*args, **kwds)



class   Thread_Status:
    """
        INIT -> RUN  ->  SYN
          \      |       /
           \     |      /
                BAD
    """
    #ACCEPT  ="ACCEPT"
    INIT    ="INIT" #just created
    #SYN     ="SYN"  #already readed all the posts
    RUN     ="RUN"  #just try to run and run to read all the post
    BAD     ="BAD"
    
    
def get_cn_now_time():
    #from datetime import datetime, timedelta, date
    
    t=datetime.datetime.utcnow() + datetime.timedelta(hours=+8)
    return t

def ascii_to_datetime(ascii_str):
    #http://www.tianya.cn/techforum/content/16/619502.shtml
    #floor 1095,only date,without time
    date_str=ascii_str
    if len(date_str) >12:
        if date_str.find("T")>0:
            #return datetime.datetime.parse_iso8601(date_str)
            return datetime.datetime.strptime(date_str,'%Y%m%dT%H:%M:%S')
        else:
            return datetime.datetime.strptime(date_str,'%Y-%m-%d %H:%M:%S')
    else:
        d =datetime.datetime.strptime(date_str,'%Y-%m-%d')
        return d
    
class Thread(db.Model):
    thread_id=db.StringProperty(required=True,default="NA")
    
    title=db.StringProperty()            
    created =db.DateTimeProperty(auto_now_add=True)    
    lst_page_url=db.StringListProperty()
    page_cnt=db.IntegerProperty(required=True,default=0)    # if FORM page,it means form counts
    chrAuthor=db.StringProperty()
    latest_post_date=db.DateTimeProperty(default    =   ascii_to_datetime("1970-01-01 00:00:00"))
    status  = db.StringProperty(required=True,default =Thread_Status.INIT)
    offset  =db.IntegerProperty(default=0)
    
    @staticmethod
    def build_thread_from_dict(dict):
        logging.info(dict.keys())
        logging.info(dict)
        logging.info("""type(dict['offset']:%s"""%str(type(dict['offset'])))
        t=Thread(   thread_id=dict['thread_id'],
                    title=xmw_decoding(dict['title']).decode('utf-8'),
                    #created= dict['created'],
                    lst_page_url=dict['lst_page_url'],
                    page_cnt=dict['page_cnt'],
                    chrAuthor=xmw_decoding(dict['chrAuthor']).decode('utf-8'),
                    #latest_post_date=dict['latest_post_date'],
                    status=dict['status'],
                    offset=dict['offset'],
                    
                )
        if dict['created'] is not None:
            t.created =ascii_to_datetime(dict['created'].__str__())
        if dict['latest_post_date'] is not None:
            t.latest_post_date=ascii_to_datetime(dict['latest_post_date'].__str__()) 
            
        return t
    def is_exist(self):
        q=Thread.all()
        q.filter('thread_id=', self.thread_id)
        t=q.get()
        if t is None:
            return False
        else:
            return True
        
    
    def to_thread_dict(self):
        dict={
                'thread_id':self.thread_id,
                'created':self.created,
                'lst_page_url':self.lst_page_url,
                'page_cnt':self.page_cnt,
                'chrAuthor':xmw_encoding(self.chrAuthor.encode('utf-8')),
                #'chrAuthor':'chrAuthor',
                'latest_post_date':self.latest_post_date,
                'status':self.status,
                'offset':self.offset,
                'title':xmw_encoding(self.title.encode('utf-8')),
                #'title':"title",
                
              }
        return dict
def get_uuid_hex():
    u=uuid.uuid4()
    return u.hex

class Page_Status:
    INIT    =0
    ACTIVE=1
    CURRENT=2
    INACTIVE=3
"""    
class Page(db.Model):
    thread_id   =db.StringProperty()
    page_id     =db.StringProperty()
    url         =db.URLProperty()
    lastest_post_date  =db.DateTimeProperty()
    last_scan   =db.DateTimeProperty()
    status      =db.IntegerProperty(default=Page_Status.INIT)
"""
class Page:
    thread_id   =None
    page_id     =None
    url         =None
    lastest_post_date  =None
    last_scan   =None
    status      =db.IntegerProperty(default=Page_Status.INIT)
    
"""
ERROR_DEBUG =0
ERROR_INFO  =1
ERROR_WARNING   =2
ERROR_ERROR =3
ERROR_CRITICAL  =4
"""

class Post(db.Model):
    """
    useless,use tianya.Post
    """
    author=db.StringProperty()
    date=db.DateTimeProperty( )
    floor=db.StringProperty()
    content=db.TextProperty()    

    url=db.StringProperty()
    
    #post_id=db.StringProperty(multiline=False, required=True,default=xmw.get_uuid_hex())
    post_id     =db.StringProperty(multiline=False, required=True)
    thread_id   = db.StringProperty (multiline=False, required=True)
    offset  =   db.IntegerProperty()


def xmw_zip_encoding(str):
    if str is None:
            return None
    str=zlib.compress(str)
    str=base64.encodestring(str)
    str=str.replace("=","@")
    str=str.replace("+","*")
    str=str.replace("\r","(")
    str=str.replace("\n","(")
    
    return str
def xmw_zip_decoding(str):
    if str is None:
        return None
    str=str.replace("@","=")
    str=str.replace("*","+")
    str=str.replace("(","\r")
    str=str.replace("\n","\n")
    str=base64.decodestring(str)
    str=zlib.decompress(str)
    return str
def xmw_decoding(str):
    if str is None:
        return None
    str=str.replace("@","=")
    str=str.replace("*","+")
    str=str.replace("(","\r")
    str=str.replace("\n","\n")
    str=base64.decodestring(str)
    #str=zlib.decompress(str)
    return str

def xmw_encoding(str):
    if str is None:
            return None
    str=base64.encodestring(str)
    str=str.replace("=","@")
    str=str.replace("+","*")
    str=str.replace("\r","(")
    str=str.replace("\n","(")
    
    return str
class RequestHandler(webapp.RequestHandler):
    def clear_sess(self):
        
        if self.__dict__.has_key('sess'):
            #logging.log( logging.INFO, "sess:%s"% str(self.sess))
            self.sess.clear()
           
                
    def xmw_encoding(self,str):
        return xmw_encoding(str)
    
    
    def xmw_decoding(self,str):
        return xmw_decoding(str)
    
    def render_template(self,template_values,template_name):
        path =  os.path.join(global_setting.base_dir, 'template/%s'%template_name)
        #path =  os.path.join(os.path.dirname(__file__), 'portal/template/error.html')
        #self.response.out.write("path:%s"%path)
        self.response.out.write(template.render(path, template_values))
        
    def render_error(self,e):
        e.log()
        template_values =  {
                            "error":e
                            } 
        self.render_template(template_values, 'error.html')  
    
    def test_and_get(self,dic,key):
        e=None
        if  not dic.has_key(key):
            e = error.ARGUMENT_FAULT("parameter %s not Found!."%str(key))
            #self.render_error(e)
            return(None,e)

        val=dic[key]
        val=val.strip()
        return (val,e)

    def get_key_from_GET(self,key):
        (val,e)=self.test_and_get(self.request.GET,key)
        return (val,e)

    def get_key_from_POST(self,key):
        (val,e)=self.test_and_get(self.request.POST,key)
        return (val,e)  


    def get_session_user(self):
        session_user =None
        if self.sess.has_key("user"):
            session_user=self.sess["user"]
        return session_user
    
    def init_session(self):
        self.sess = sessions.Session()
        self.cookie_sess = sessions.Session(writer="cookie") 
        
            
def main():
    pass

if __name__ == "__main__":      
    main()
        

    